from mutagen import File
from mutagen.mp3 import MP3
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3NoHeaderError
import os

class Informer:
    def getInfo(self, url):
        try:
            audio = File(url)
        except Exception, e:
            return None, None, None

        if audio is not None:
            info = audio.info
            tags = audio.tags

            if isinstance(audio, MP3):
                try:
                    tags = EasyID3(url)
                except ID3NoHeaderError, e:
                    print e

            if tags is None:
                tags = {'title': [os.path.basename(url)]}

            return url, info, tags
        else:
            return None, None, None


    def hasAudio(self, url):
        try:
            audio = File(url)
        except Exception, e:
            return True

        if audio is None:
            return False
        else:
            return True


    def getDirContent(self, dirPath):
        '''
            get info of all files in dir and subdirs
        '''

        content = []

        for root, dirs, files in os.walk(dirPath):
            for name in files:
                filePath = os.path.join(root, name)
                url, info, tags = self.getInfo(filePath)
                if info:
                    content.append([url, info, tags])

        return content
